import wx from 'weixin-js-sdk'
import axios from '@/utils/request'

export default { // 获取微信支付SDK的签名
    getWxPaySign(params) {
        return new Promise((resolve) => {
            // 发起请求获取签名
            axios.get('/service/order/testPay').then((data) => {
                if (data.code === 0) {
                    // 配置微信JS SDK
                    wx.config({
                            debug: false,
                            appId: data.result.appId,
                            timestamp: data.result.timestamp,
                            nonceStr: data.result.nonceStr,
                            signature: data.result.signature,
                            jsApiList: [
                                'chooseWXPay'
                            ]
                        })
                        // 配置完成后返回一个resolve
                    wx.ready(() => {
                        resolve()
                    })
                }
            })
        })
    },

    // 发起微信支付
    wxPay(params) {
        return new Promise((resolve, reject) => {
            // 调用微信支付
            wx.chooseWXPay({
                timestamp: params.timestamp,
                nonceStr: params.nonceStr,
                package: params.package,
                signType: params.signType,
                paySign: params.paySign,
                success: (res) => {
                    // 支付成功时返回resolve
                    resolve(res)
                },
                fail: (err) => {
                    // 支付失败时返回reject
                    reject(err)
                }
            })
        })
    },
}